<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${ dataItem.deviceNumber || '' }-详情`"
		width="1200px"
		:show-confirm-btn="false"
		:show-cancel-btn="false"
		:show-close-btn="true"
		@on-close="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
	>
		<div class="flex-end-center margin-bottom-10">
			<jk-date-picker v-model="searchParams.fromDate" type="date" :disabled-future-time="true" :clearable="false" placeholder="班次开始日期" size="small" class="search-bar-item-size2 margin-5-0 item-gap"></jk-date-picker>
			<jk-select v-model="searchParams.fromShiftCode" :option-list="searchOptionConfig.shiftList" size="small" placeholder="开始班次" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
			<jk-date-picker v-model="searchParams.toDate" type="date" :disabled-future-time="true" :clearable="false" placeholder="班次结束日期" size="small" class="search-bar-item-size2 margin-5-0 item-gap"></jk-date-picker>
			<jk-select v-model="searchParams.toShiftCode" :option-list="searchOptionConfig.shiftList" size="small" placeholder="结束班次" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
			<!--<jk-select v-model="searchParams.workshopId" :clearable="false" placeholder="区域" :option-list="workshopList" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onDateChange"></jk-select>-->
			<!-- <jk-date-picker v-model="searchParams.belongDates" type="daterange" :disabled-future-time="true" :clearable="false" placeholder="日期" size="small" class="search-bar-item-size4 item-gap"></jk-date-picker>
			<jk-select v-model="searchParams.shiftCode" :option-list="searchOptionConfig.shiftList" size="small" placeholder="班次" class="search-bar-item-size1 item-gap"></jk-select> -->
			<!-- <el-time-picker
				v-model="pickerTime"
				is-range
				value-format="HH:mm:ss"
				size="small"
				range-separator="至"
				style="width: 280px;"
				class="margin-5-0 item-gap"
				start-placeholder="班次开始时间"
				end-placeholder="班次结束时间"
			>
			</el-time-picker> -->
			<!--<jk-select v-model="searchParams.duration" placeholder="时长排序" :option-list="[{id: 'asc', name:'正序'},{id: 'desc', name:'倒序'}]" size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>-->
			<jk-input v-model="searchParams.deviceNumber" class="search-bar-item-size2 item-gap" placeholder="机台号" size="small" clearable @on-enter="onSearchBtn" />
			<jk-select v-model="searchParams.position" label-key-name="id" placeholder="面位" :option-list="searchOptionConfig.machineFaceList" size="small" class="search-bar-item-size1 item-gap"></jk-select>
			<!--<jk-input v-model="searchParams.startIngotNo" class="search-bar-item-size1 margin-5-0 item-gap" placeholder="开始锭号" size="small" clearable @blur="onIngotNumberChange($event,'startIngotNo')" />-->
			<!--<jk-input v-model="searchParams.endIngotNo" class="search-bar-item-size1 margin-5-0 item-gap" placeholder="结束锭号" size="small" clearable @blur="onIngotNumberChange($event,'endIngotNo')" />-->
			<jk-search-button @click="onSearchBtn"></jk-search-button>
		</div>
		<jk-table
			border
			:data="tableData"
			:footer-method="footerMethod"
			:show-footer="true"
			:loading="tableLoading"
			:height="400"
		>
			<vxe-column title="日期时间" align="left" field="belongDate" :width="140" />
			<vxe-column title="班次" align="left" field="shiftName" :min-width="80" />
			<vxe-column title="屏幕班次" align="left" field="screenShiftName" :min-width="80" />
			<vxe-column title="机台号" align="left" field="deviceNumber" :min-width="80" />
			<vxe-column title="面位" align="left" field="position" :min-width="80" />
			<vxe-column title="锭号" align="left" field="ingotNo" :min-width="80" />
			<vxe-column title="断头开始时间" align="left" field="startTime" :width="160" />
			<vxe-column title="断头结束时间" align="left" field="endTime" :width="160" />
			<vxe-column title="时长(分)" align="left" field="duration" :min-width="80">
				<template #header>
					<div style="display: flex">
						<span>时长(分)</span>
						<span style="cursor: pointer; display: flex; align-items: center;" @click="toggleSort('duration')">
							{{ sortOrders.duration === "asc" ? "⬆" : sortOrders.duration === "desc" ? "⬇" : "⇅" }}
						</span>
					</div>
				</template>
			</vxe-column>
		</jk-table>
		<!-- 分页组件 -->
		<footer ref="box2" class="flex-end-center margin-top-10">
			<jk-page
				:page-index="searchParams.pageNo"
				:page-sizes="searchParams.pageSizes"
				:page-size="searchParams.pageSize"
				:total="totalCount"
				@on-change="onPageChange"
			/>
		</footer>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { spinBrokenHeadWeakTwistSortSubViewPage } from '../../../../api/statistic/spindleReports';
    import handlerCache from '@/mixins/handler-cache';
    import XEUtils from 'xe-utils';

    export default {
        name: 'MachineArchives',
        props: {
            searchOptionConfig: {
                type: Object,
                default() {
                    return {
                        shiftList: [],
                        machineFaceList: []
                    };
                }
            },
            // isRealTime: {
            //     type: Boolean,
            //     default: false
            // },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataItem: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        mixins: [calHeight, handlerCache],
        data() {
            return {
                pickerTime: [],
                totalCount: null,
                apiItem: {
                    'page': spinBrokenHeadWeakTwistSortSubViewPage
                },
                sortOrders: {
                    duration: null
                },
                searchParams: {},
                showDialog: false,
                tableLoading: false,
                tableData: []
            };
        },
        methods: {
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                this.$set(this.sortOrders, 'duration', null);
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            toggleSort(field) {
                // 重置所有排序状态
                Object.keys(this.sortOrders).forEach((key) => {
                    if (key !== field) {
                        this.sortOrders[key] = null;
                    }
                });
                // 切换当前字段的排序状态
                if (
                    this.sortOrders[field] === null
                    // ||
                    // this.sortOrders[field] === 'desc'
                ) {
                    this.sortOrders[field] = 'asc';
                    this.searchParams.ascField = field;
                    this.searchParams.descField = null;
                } else if (this.sortOrders[field] === 'asc') {
                    this.sortOrders[field] = 'desc';
                    this.searchParams.ascField = null;
                    this.searchParams.descField = field;
                } else {
                    this.sortOrders[field] = null;
                    this.searchParams.ascField = null;
                    this.searchParams.descField = null;
                }
                if (!this.searchParams.sortType) {
                    this.getListRequest();
                }
            },
            footerMethod({ columns, data }) {
                const keys = ['ingotNo', 'duration'];
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return '合计';
                        }
                        if (columnIndex === 5) {
                            return this.tableData.length ? this.tableData[0].totalBrokenQty : '';
                        }
                        if (columnIndex === 8) {
                            return this.tableData.length ? this.tableData[0].totalBrokenTime : '';
                        }
                        if (keys.includes(column.field)) {
                            return XEUtils.sum(data, column.field);
                        }
                        return null;
                    })
                ];
            },
            clearCacheMethod() {
                Object.assign(this.$data, this.$options.data());
            },
            getListRequest() {
                this.tableData = [];
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                // params.realtimeBroken = this.isRealTime;
                // params.belongDates = params.belongDates.map((date, index) => {
                //     const defaultTime = index === 0 ? '00:00:00' : '23:59:59';
                //     console.log(this.pickerTime, ' ====== ');
                //     const time = this.pickerTime && this.pickerTime.length > 0 ? this.pickerTime[index] : defaultTime;
                //     return `${date} ${time}`;
                // });
                return this.apiItem['page'](params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            }
        },
        watch: {
            // 'searchParams.shiftCode': {
            //     handler(val) {
            //         const { shiftList } = this.searchOptionConfig;
            //         const selectedShift = shiftList.find(i => i.id === val);
            //         if (selectedShift) {
            //             const { beginHour, endHour } = selectedShift;
            //             this.pickerTime = [beginHour, endHour]; // 直接赋值
            //             console.log(this.pickerTime, ' this.pickerTime');
            //         }
            //     }, immediate: true
            // },

            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    const { fromDate, toDate } = this.dataItem;
                    this.searchParams = JSON.parse(JSON.stringify(this.dataItem));
                    this.searchParams.fromDate = fromDate;
                    this.searchParams.toDate = toDate;
                    if (this.searchParams.sortType === 'MINMAX') {
                        this.searchParams.descField = 'duration';
                    }
                    this.$nextTick(() => {
                        this.getListRequest();
                    });
                }
            }

        }
    };
</script>
